package com.sky.service.Impl;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WorkspaceService workspaceService;


    @Override
    public TurnoverReportVO getTurnover(LocalDate begin, LocalDate end) {
//        查询段时间内销售量
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
//        获取每天日期
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);//获得日期后一天的日期
            log.info("AAA" + begin);
            dateList.add(begin);
        }
        List<Double> turnoverList = new ArrayList<>();
        for (LocalDate date : dateList) {
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("status", Orders.COMPLETED);
            map.put("begin", beginTime);
            map.put("end", endTime);
//            计算销售额
            Double turnover = orderMapper.sumTurnover(map);
//            if (turnover == null){
//                turnover = 0.0;
//            }
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
//        获取用户总数和新增数
        List<Integer> userNumbers = new ArrayList<>();
        List<Integer> newUsers = new ArrayList<>();

        for (LocalDate localDate : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
            newUsers.add(userMapper.countByCount(map));
            map.put("begin", null);
            userNumbers.add(userMapper.countByCount(map));
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(localDates, ","))
                .newUserList(StringUtils.join(newUsers, ","))
                .totalUserList(StringUtils.join(userNumbers, ","))
                .build();
    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        List<LocalDate> localDates = new ArrayList<>();
        localDates.add(begin);
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            localDates.add(begin);
        }
//        每天订单总数集合
        List<Integer> orderCountList = new ArrayList<>();
//        每天有效订单总数集合
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate localDate : localDates) {
            LocalDateTime beginTime = LocalDateTime.of(localDate, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(localDate, LocalTime.MAX);
            Map map = new HashMap();
            map.put("begin", beginTime);
            map.put("end", endTime);
//            每天订单数
            Integer orderCount = orderMapper.getOrderCount(map);
//            每天有效订单数
            map.put("status", Orders.COMPLETED);
            Integer validOrderCount = orderMapper.getOrderCount(map);
            orderCountList.add(orderCount);
            validOrderCountList.add(validOrderCount);
        }
//        段时间内总订单数  reduce是求和
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        System.out.println(orderCountList.stream().reduce(Integer::sum).get());
        System.out.println(orderCountList.size());
        System.out.println(orderCountList.stream().reduce(Integer::sum).get().equals(orderCountList.size()));

//        段时间内的总有效订单数
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
//        订单完成率
        Double orderPC = 0.0;
        if (totalOrderCount != 0) {
            orderPC = validOrderCount.doubleValue() / totalOrderCount;
        }
        return OrderReportVO.builder()
                .dateList(StringUtils.join(localDates, ","))
                .orderCountList(StringUtils.join(orderCountList, ","))
                .validOrderCountList(StringUtils.join(validOrderCountList, ","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderPC)
                .build();
    }

    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);
        List<GoodsSalesDTO> goodsSalesDTOList = orderMapper.getSalesTop10(beginTime, endTime);

        String nameList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList()), ",");
        String numberList = StringUtils.join(goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList()), ",");

        return SalesTop10ReportVO.builder()
                .nameList(nameList)
                .numberList(numberList)
                .build();
    }

    @Override
    public void exportBusinessData(HttpServletResponse response) {
        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        // 查询概览的运营数据，30天数据之和
        BusinessDataVO businessData = workspaceService.BusinessData(LocalDateTime.of(begin, LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板2.xlsx");
        // 创建excel
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream()).withTemplate(inputStream).build()) {
            // 创建sheet
            WriteSheet writeSheet = EasyExcel.writerSheet().build();
            BusinessDataVO businessData1;
            List<BusinessDataDetailVO> list = new ArrayList<>();

             //获取每天的数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                businessData1 = workspaceService.BusinessData(LocalDateTime.of(date, LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                BusinessDataDetailVO vo = new BusinessDataDetailVO();
                vo.setDate(date);
                vo.setNewUsers_day(businessData1.getNewUsers());
                vo.setTurnover_day(businessData1.getTurnover());
                vo.setOrderCompletionRate_day(businessData1.getOrderCompletionRate());
                vo.setUnitPrice_day(businessData1.getUnitPrice());
                vo.setValidOrderCount_day(businessData1.getValidOrderCount());
                list.add(vo);
            }
            // 把每天的数据写入excel
            excelWriter.fill(list, writeSheet);
            // 把概览数据写入excel
            excelWriter.fill(businessData, writeSheet);
        } catch (Exception e) {
            log.error("导出excel异常", e.getMessage());
            e.printStackTrace();
        }


    }
}
